<?php



class gbs
{
    public $url ='http://wx.cnipc.top:17088';
    public $name ='admin';
    public $pwd ='666666';
    public $token = '';
    public $path=[
        'login'=>'/api/web/login',
        'arealist'=>'/api/web/arealist',
        'devicelist'=>'/api/web/devicelist',
        'channellist'=>'/api/web/channellist',
        'snapshot'=>'/hsdata/sip/snapshot'
    ];

    public function __construct()
    {
        $login = file_get_contents('login.txt');
        $login = @json_decode($login,true);
        if(!$login or $login['expire'] < time()+60){
            $login = $this->login();
            if($login['ret'] && $login['info']['code']==0){
                $login = $login['info'];
                $login['time'] =time();
                $login['expire'] += time();
                file_put_contents('login.txt',json_encode($login));
            } else {
                echo '登录失败!';die;
            }
        }
        $this->token = $login['token'];
    }

    public function login(){
        $data = $this->sendRequest($this->url.$this->path['login'],[
            "cmd"=>"down_login",
            'name'=>$this->name,
            'pwd'=>$this->pwd,
        ],[]);
        return $data;
    }
    public function arealist(){
        $data = $this->sendRequest($this->url.$this->path['arealist'],[
            "cmd"=>"down_getarea",
            "token"=>$this->token
        ],[]);
        return $data;
    }
    public function devicelist($area,$gb_no ='',$page = 1,$size = 20){
        $data = $this->sendRequest($this->url.$this->path['devicelist'],[
            "cmd"=>"down_devicelist",
            "pageno"=>$page,
            "pagesize"=>$size,
            "gb_no"=>$gb_no,
            "area_gbno"=>$area,
            "token"=>$this->token
        ],[]);
        return $data;
    }
    public function channellist($belong_device_gbno,$gb_no ='',$page = 1,$size = 20){
        $data = $this->sendRequest($this->url.$this->path['channellist'],[
            "cmd"=>"down_channellist",
            "pageno"=>$page,
            "pagesize"=>$size,
            "belong_device_gbno"=>$belong_device_gbno,
            "gb_no"=>$gb_no,
            "token"=>$this->token
        ],[]);
        return $data;
    }
    public function snapshot($deviceid,$channelid){
        $data = $this->sendRequest($this->url.$this->path['snapshot'],[
            "cmd"=>"down_getsnap",
            "deviceid"=>$deviceid,
            "channelid"=>$channelid
        ],[]);
        echo json_encode([
            "cmd"=>"down_getsnap",
            "deviceid"=>$deviceid,
            "channelid"=>$channelid
        ]);
        return $data;
    }
    public function sendRequest($url, $params = [],  $options = [])
    {
        $json = 1;
        $method = 'POST';
        $method = strtoupper($method);
        $protocol = substr($url, 0, 5);
        $params = $query_string = is_array($params) ? json_encode($params) : $params;

        $ch = curl_init();
        $defaults = [];
        if ('GET' == $method) {
            $geturl = $query_string ? $url . (stripos($url, "?") !== false ? "&" : "?") . $query_string : $url;
            $defaults[CURLOPT_URL] = $geturl;
        } else {
            $defaults[CURLOPT_URL] = $url;
            if ($method == 'POST') {
                $defaults[CURLOPT_POST] = 1;
            } else {
                $defaults[CURLOPT_CUSTOMREQUEST] = $method;
            }
            $defaults[CURLOPT_POSTFIELDS] = $params;
        }

        $defaults[CURLOPT_HEADER] = false;
        $defaults[CURLOPT_USERAGENT] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.98 Safari/537.36";
        $defaults[CURLOPT_FOLLOWLOCATION] = true;
        $defaults[CURLOPT_RETURNTRANSFER] = true;
        $defaults[CURLOPT_CONNECTTIMEOUT] = 20;//20秒链接时间
        $defaults[CURLOPT_TIMEOUT] = 60;//总的执行时间，包含CURLOPT_CONNECTTIMEOUT时间

        // disable 100-continue
        if ($json){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        } else {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
        }
        if ('https' == $protocol) {
            $defaults[CURLOPT_SSL_VERIFYPEER] = false;
            $defaults[CURLOPT_SSL_VERIFYHOST] = false;
        }

        curl_setopt_array($ch, (array)$options + $defaults);

        $ret = curl_exec($ch);
        $err = curl_error($ch);
        if (false === $ret || !empty($err)) {
            $errno = curl_errno($ch);
            $info = curl_getinfo($ch);
            curl_close($ch);
            return [
                'ret'   => false,
                'errno' => $errno,
                'msg'   => $err,
                'info'  => $info,
            ];
        }
        curl_close($ch);
        return [
            'ret' => true,
            'info' => is_array($ret) ? $ret : json_decode($ret,1)
        ];
    }

}


while(true){
    $arealist = (new gbs)->arealist();
    if($arealist['ret'] && $arealist['info']['code']== 0){
        foreach($arealist['info']['list_data'] as $area){
            $devicelist = (new gbs)->devicelist($area['area_gbno']);
            if($devicelist['ret'] && $devicelist['info']['code']== 0){
                foreach($devicelist['info']['list_data'] as $device){
                    $channellist = (new gbs)->channellist($device['gb_no']);
                    if($channellist['ret'] && $channellist['info']['code']== 0){
                        foreach($channellist['info']['list_data'] as $channel){
                            $data=[
                                'deviceid'=>$channel['belong_device_gbno'],
                                'channelid'=>$channel['gb_no'],
                                'is_online'=>$device['online']?1:0,
                                'starttime'=>date('Y/m/d/H/i/s'),
                                'endtime'=>'',
                                'status'=>0,//0开始抓图 1抓图结束 2未抓到图片 3抓到图片 4请求接口问题
                                'url'=>'',
                            ];
                            $snapshot = (new gbs())->snapshot($channel['belong_device_gbno'],$channel['gb_no']);
                            sleep(10);
                            $snapshot = (new gbs())->snapshot($channel['belong_device_gbno'],$channel['gb_no']);
                            sleep(15);   
                            $snapshot = (new gbs())->snapshot($channel['belong_device_gbno'],$channel['gb_no']);
                            $data['endtime']=date('Y/m/d/H/i/s');
                            $data['status']=1;
                            if($snapshot['ret']) {
                                if($snapshot['info']['code'] == 0){
                                    $data['status']=3;
                                    $data['url']=$snapshot['info']['url'];
                                } else {
                                    $data['status']=2;
                                }
                            } else {
                                $data['status']=4;
                            }
                            file_put_contents('./log/'.date('Y-m-d').'.log', join(' ',$data).PHP_EOL,FILE_APPEND);
                        }                   
                    } else{
                        echo date('Y-m-d H:i:s').'-通道列表获取失败!'. PHP_EOL;
                        continue;
                    }
                    sleep(35);
                }
            } else{
                echo date('Y-m-d H:i:s').'-设备列表获取失败!'. PHP_EOL;
                continue;
            }
        }

    } else {
        echo date('Y-m-d H:i:s').'-地区列表获取失败!'. PHP_EOL;
        sleep(10); 
    }
}

